/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aviso.facade;

import aviso.entity.Advert;
import aviso.entity.UserCartRecord;
import aviso.entity.UserHistoryRecord;
import aviso.entity.UserName;
import java.util.Calendar;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author avgusti
 */
@Stateless
public class UserNameFacade extends AbstractFacade<UserName> {

    @PersistenceContext(unitName = "aviso")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public UserNameFacade() {
        super(UserName.class);
    }

    public boolean isNameExist(String name) {
        Query q = em.createQuery("select count(*) from UserName  u where u.name=:un");
        int count = ((Long) q.setParameter("un", name).getSingleResult()).intValue();
        if (count > 0) {
            return true;
        }
        return false;
    }

    public UserName getUserByName(String name) {
        Query q = em.createQuery("select u from UserName  u where u.name=:un");
        try{
        UserName user = (UserName) q.setParameter("un", name).getSingleResult();
        return user;
        }
        catch(NoResultException e){
            return null;
        }
        
    }
    // @TransactionAttribute(TransactionAttributeType.REQUIRED)

    public UserName addHistoryRercord(Long userID, Long advID) {
        UserName un = em.find(UserName.class, userID);
        Advert adv = em.find(Advert.class, advID);
        UserHistoryRecord hr;
        if (un.getHistory().containsKey(advID)) {
            hr = un.getHistory().get(advID);
            hr.setTimestamp(Calendar.getInstance());
        } else {
            hr = new UserHistoryRecord();
            un.getHistory().put(advID, hr);
            hr.setUserName(un);
            hr.setAdvert(adv);
            hr.setTimestamp(Calendar.getInstance());
            em.persist(hr);
        }
        while (un.getHistory().size() >= un.getHistoryLength()) {
                UserHistoryRecord[] records = un.getHistory().values().toArray(new UserHistoryRecord[0]);
                Long t = Long.MAX_VALUE; Long id=0l;
                for (UserHistoryRecord i : records) {
                    if (i.getTimestamp().getTimeInMillis() < t) {
                        t = i.getTimestamp().getTimeInMillis();
                        id=i.getAdvert().getId();
                    }
                }
                un.getHistory().remove(id);
            }
        em.merge(hr);
        em.merge(un);
        em.flush();
        return un;
    }

    public UserName verifyEmail(Object newValue) {
        UserName tmp =query_getSingleResult(em.createNamedQuery("UserName.VerifyEmail").setParameter("hash", newValue), UserName.class);
        if (tmp != null) {
            tmp.setActive(Boolean.TRUE);
            tmp.setEmailHash(null);
            edit(tmp);
            return tmp;
        }
        return null;
    }

    public UserName addCartRercord(Long id, Long advID) {
        UserName un = em.find(UserName.class, id);
        Advert adv = em.find(Advert.class, advID);
        UserCartRecord ucr = new UserCartRecord();
        ucr.setAdvert(adv);
        ucr.setUserName(un);
        //em.persist(ucr);
        un.getCart().put(advID, ucr);
        un = em.merge(un);
        return un;
    }

    public UserName removeCartRercord(Long id, Long advID) {
        UserName un = em.find(UserName.class, id);
        un.getCart().remove(advID);
        un = em.merge(un);
        return un;
    }

    public UserName cleanCart(UserName un) {
        em.merge(un);
        un.getCart().clear();
        un = em.merge(un);
        return un;
    }
    public UserName cleanHistory(UserName un) {
        em.merge(un);
        un.getHistory().clear();
        un = em.merge(un);
        return un;
    }
}
